package com.cykj.faceledtv.ui.main;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.cykj.faceledtv.MyApp;
import com.cykj.faceledtv.R;
import com.cykj.faceledtv.adapter.TeamAdapter;
import com.cykj.faceledtv.adapter.decoration.DividerItemDecoration;
import com.cykj.faceledtv.common.Constants;
import com.cykj.faceledtv.data.db.model.UserData;
import com.cykj.faceledtv.entity.RecordData;
import com.cykj.faceledtv.listener.FaceListener;
import com.cykj.faceledtv.service.FaceLedService;
import com.cykj.faceledtv.ui.base.BaseActivity;
import com.cykj.faceledtv.utils.GlideUtils;
import com.cykj.faceledtv.utils.IpUtils;
import com.cykj.faceledtv.utils.MacUtils;
import com.cykj.faceledtv.widget.AdapterEmptyView;
import com.cykj.faceledtv.widget.LoopRecyclerView;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;

import static java.lang.System.currentTimeMillis;

/**
 * @author jzh
 * @date 2019/05/09 15:53
 */
public class MainActivity extends BaseActivity implements FaceListener, MainMvpView {
    @BindView(R.id.ac_main_mac)
    TextView macTv;
    @BindView(R.id.ac_main_ip)
    TextView ipTv;
    @BindView(R.id.ac_main_led)
    TextView ledTv;
    @BindView(R.id.ac_main_time)
    TextView timeTv;
    @BindView(R.id.ac_main_date)
    TextView dateTv;
    @BindView(R.id.ac_main_today_weather)
    TextView todayWeatherTv;
    @BindView(R.id.ac_main_tomorrow_weather)
    TextView tomorrowWeatherTv;
    @BindView(R.id.ac_main_present)
    TextView presentTv;
    @BindView(R.id.ac_main_arrival)
    TextView arrivalTv;
    @BindView(R.id.ac_main_out)
    TextView outTv;
    @BindView(R.id.ac_main_img)
    ImageView photoIv;
    @BindView(R.id.ac_main_name)
    TextView nameTv;
    @BindView(R.id.ac_main_punch_time)
    TextView punchTimeTv;
    @BindView(R.id.ac_main_body_temp)
    TextView bodyTemp;
    //    @BindView(R.id.ac_main_work_type)
//    TextView workTypeTv;
//    @BindView(R.id.ac_main_team)
//    TextView teamTv;
//    @BindView(R.id.ac_main_leader)
//    TextView leaderTv;
    @BindView(R.id.ac_main_recycler)
    LoopRecyclerView mRecycler;
    @BindView(R.id.ac_main_today)
    TextView todayTv;
    @BindView(R.id.ac_main_tomorrow)
    TextView tomorrowTv;
    @BindView(R.id.ac_main_today_iv)
    ImageView todayIv;
    @BindView(R.id.ac_main_tomorrow_iv)
    ImageView tomorrowIv;
    @BindView(R.id.ac_site_name)
    TextView siteNameTv;
//    @BindView(R.id.ac_main_in_out_type)
//    TextView inoutTypeTv;

    private FaceLedService service;
    private ServiceConnection sc;
    private boolean isBindServiceSuccess;
    private boolean isResume = false;
    private ExecutorService timeEs;
    private MyTimeHandler timeHandler;
    @Inject
    MainPresenter<MainMvpView> mPresenter;
    private String city = "深圳市";

    private Handler mMainHandler;

    /**
     * 天气定时获取线程
     */
    private ScheduledExecutorService weatherEs;
    private String inOutAdv, freeAdv;


    public static final int TIME_WHAT = 200;
    public static final int INOUT_WHAT = 300;
    public static final int FREE_WHAT = 400;
    public static final int CLEAR_DATA_WHAT = 500;

    private TeamAdapter adapter;

    @Override
    protected int getLayoutId() {
        return R.layout.ac_main;
    }

    @Override
    protected void initWidget() {
        setUnBinder(ButterKnife.bind(this));
        getActivityComponent().inject(this);
        mPresenter.onAttach(this);
        inOutAdv = MyApp.getInstance().mDataManager.getInOutAdv();
        freeAdv = MyApp.getInstance().mDataManager.getFreeAdv();
        mMainHandler = new Handler(getMainLooper());
        timeHandler = new MyTimeHandler(this);
        bindService();
        Intent intent = getIntent();
        if (intent != null) {
            city = intent.getStringExtra(Constants.PARAMS);
        }
        String mac = MacUtils.getMac();
        if (!TextUtils.isEmpty(mac) && !mac.equals("02:00:00:00:00")) {
            macTv.setText("MAC:" + mac);
        }
        String siteName = MyApp.getInstance().mDataManager.getSiteName();
        if (!TextUtils.isEmpty(siteName)) {
            siteNameTv.setText(siteName);
        }
        String ip = IpUtils.getIp();
        if (!TextUtils.isEmpty(ip)) {
            ipTv.setText("IP:" + IpUtils.getIp());
        }
        bodyTemp.setText("体温：");
//        workTypeTv.setText("工种：");
//        teamTv.setText("班组：");
//        leaderTv.setText("班组长：");
//        inoutTypeTv.setText("进出类型：");
        if (!TextUtils.isEmpty(freeAdv)) {
            ledTv.setText(freeAdv);
        }
        initRecycler();
        startWeather();
    }

    private void initRecycler() {
        mRecycler.addItemDecoration(new DividerItemDecoration(this));
        List<RecordData> data = new ArrayList<>();
        adapter = new TeamAdapter(data);
        adapter.openLoadAnimation();
        adapter.setEmptyView(AdapterEmptyView.getEmptyView(this));
        mRecycler.setAdapter(adapter);
        mRecycler.start();
    }

    private void startWeather() {
        weatherEs = Executors.newSingleThreadScheduledExecutor();
        weatherEs.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (mPresenter != null) {
                    mPresenter.doGetWeather(MainActivity.this, city);
                }
            }
        }, 0, 30, TimeUnit.MINUTES);
    }

    @Override
    protected void onResume() {
        super.onResume();
        isResume = true;
        //启动时间的线程
        startTimeThread();
    }

    @Override
    public void onSuccess(String todayMsg, String tomorrowMsg, String todayCode, String tomorrowCode) {
        if (!isResume) {
            return;
        }
        todayTv.setVisibility(View.VISIBLE);
        tomorrowTv.setVisibility(View.VISIBLE);
        todayWeatherTv.setText(todayMsg);
        tomorrowWeatherTv.setText(tomorrowMsg);
        if (!TextUtils.isEmpty(todayCode)) {
            try {
                todayIv.setImageResource(getResources().getIdentifier("weather" + todayCode,
                        "drawable", getPackageName()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (!TextUtils.isEmpty(tomorrowCode)) {
            try {
                tomorrowIv.setImageResource(getResources().getIdentifier("weather" + tomorrowCode,
                        "drawable", getPackageName()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取到进出记录
     *
     * @param userData 用户数据
     */
    @Override
    public void onRecord(final UserData userData, final RecordData data) {
        if (!isResume) {
            return;
        }
        mMainHandler.post(new Runnable() {
            @Override
            public void run() {
                //发送广告语
                if (timeHandler != null) {
                    timeHandler.sendEmptyMessage(INOUT_WHAT);
                }
                if (!TextUtils.isEmpty(userData.getUserName())) {
                    nameTv.setText(userData.getUserName());
                }
                if (!TextUtils.isEmpty(userData.getImgPath())) {
                    GlideUtils.loadImage(MainActivity.this, userData.getImgPath(), photoIv);
                }
                if (data.getInOutTime() != null) {
                    try {
                        punchTimeTv.setText(DateFormat.format("yyyy-MM-dd HH:mm:ss", data.getInOutTime()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (data.getTemperature() !=null) {
                    bodyTemp.setText(getString(R.string.bodyTem,data.getTemperature()));
                }

                if (!TextUtils.isEmpty(userData.getWorkerType())) {
//                    workTypeTv.setText(getString(R.string.workType, userData.getWorkerType()));
                }
                if (!TextUtils.isEmpty(userData.getTeamName())) {
//                    teamTv.setText(getString(R.string.team, userData.getTeamName()));
                }
                if (!TextUtils.isEmpty(userData.getAdminName())) {
//                    leaderTv.setText(getString(R.string.teamLeader, userData.getAdminName()));
                }
                if (data.getInOutType() != null) {
//                    inoutTypeTv.setText(getString(R.string.inoutType, data.getInOutType() == 0 ? "进场" : "出场"));
                }
                if (data.getEnter() != null) {
                    arrivalTv.setText("" + data.getEnter() + "");
                }
                if (data.getOutNum() != null) {
                    outTv.setText("" + data.getOutNum() + "");
                }
                if (data.getInNum() != null) {
                    presentTv.setText("" + data.getInNum() + "");
                }
                if (data.getTeamId() == null) {
                    return;
                }
                List<RecordData> recordDatas = adapter.getData();
                if (recordDatas.size() <= 0) {
                    adapter.addData(data);
                    if (mRecycler != null) {
                        mRecycler.setDataCount(adapter.getData().size());
                    }
                } else {
                    for (int i = 0; i < recordDatas.size(); i++) {
                        if (recordDatas.get(i).getTeamId().equals(data.getTeamId())) {
                            adapter.remove(i);
                            adapter.addData(data);
                            return;
                        }
                    }
                    adapter.addData(data);
                    if (mRecycler != null) {
                        mRecycler.setDataCount(adapter.getData().size());
                    }
                }
            }
        });
    }

    @Override
    public void onAdvChange(String inOutAdv, final String freeAdv) {
        this.inOutAdv = inOutAdv;
        this.freeAdv = freeAdv;
        if (!isResume) {
            return;
        }
        mMainHandler.post(new Runnable() {
            @Override
            public void run() {
                if (TextUtils.isEmpty(nameTv.getText().toString())) {
                    if (!TextUtils.isEmpty(freeAdv)) {
                        ledTv.setText(freeAdv);
                    }
                }
            }
        });
    }

    @Override
    public void onSiteNameChange(final String siteName) {
        mMainHandler.post(new Runnable() {
            @Override
            public void run() {
                siteNameTv.setText(siteName);
            }
        });

    }


    private static class MyTimeHandler extends Handler {
        private WeakReference<MainActivity> mWeakReference;

        private MyTimeHandler(MainActivity pWeakReference) {
            mWeakReference = new WeakReference<>(pWeakReference);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case TIME_WHAT:
                    if (mWeakReference.get() != null) {
                        mWeakReference.get().timeTv.setText(DateFormat.format("HH:mm:ss", (long) msg.obj).toString());
                        mWeakReference.get().dateTv.setText(DateFormat.format("MM月dd日 EEEE",
                                (long) msg.obj).toString());
                    }
                    break;
                case INOUT_WHAT:
                    removeMessages(FREE_WHAT);
                    removeMessages(CLEAR_DATA_WHAT);
                    sendEmptyMessageDelayed(CLEAR_DATA_WHAT, 30000);
                    MainActivity activity = mWeakReference.get();
                    if (activity != null) {
                        if (!TextUtils.isEmpty(activity.inOutAdv)) {
                            activity.ledTv.setText(activity.inOutAdv);
                        }
                    }
                    sendEmptyMessageDelayed(FREE_WHAT, 30000);
                    break;
                case FREE_WHAT:
                    MainActivity ac = mWeakReference.get();
                    if (ac != null) {
                        if (!TextUtils.isEmpty(ac.freeAdv)) {
                            ac.ledTv.setText(ac.freeAdv);
                        }
                    }
                    break;
                //清空数据
                case CLEAR_DATA_WHAT:
                    clearData();
                    break;
                default:
                    break;
            }
        }

        private void clearData() {
            MainActivity ac = mWeakReference.get();
            if (ac == null || ac.isFinishing() || !ac.isResume) {
                return;
            }
            ac.nameTv.setText("");
//            ac.photoIv.setImageResource(R.drawable.normal);
            ac.photoIv.setImageResource(R.drawable.student);
            ac.punchTimeTv.setText("");
            ac.bodyTemp.setText("体温：");
//            ac.workTypeTv.setText("工种：");
//            ac.teamTv.setText("班组：");
//            ac.leaderTv.setText("班组长：");
//            ac.inoutTypeTv.setText("进出类型：");
        }

    }

    /**
     * 开启时间的线程任务
     */
    private void startTimeThread() {
        if (timeEs == null || timeEs.isShutdown()) {
            timeEs = Executors.newSingleThreadExecutor();
        }
        timeEs.execute(new Runnable() {
            @Override
            public void run() {
                while (isResume) {
                    try {
                        Message msg = Message.obtain();
                        msg.obj = currentTimeMillis();
                        msg.what = TIME_WHAT;
                        // 每隔1秒发送一个msg给mHandler
                        if (timeHandler != null) {
                            timeHandler.sendMessage(msg);
                        }
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        isResume = false;
    }

    private void bindService() {
        if (service != null) {
            return;
        }
        sc = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                MainActivity.this.service = ((FaceLedService.MyBinder) service).getService();
                MainActivity.this.service.setFaceListener(MainActivity.this);
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                service = null;
            }
        };
        isBindServiceSuccess = bindService(new Intent(this, FaceLedService.class), sc, BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isResume = false;
        mPresenter.onDetach();
        if (null != mRecycler) {
            mRecycler.stop();
        }
        if (sc != null && isBindServiceSuccess) {
            unbindService(sc);
        }
        if (mMainHandler != null) {
            mMainHandler.removeCallbacksAndMessages(null);
        }
        if (timeEs != null && !timeEs.isShutdown()) {
            try {
                timeEs.shutdownNow();
                timeEs = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (timeHandler != null) {
            timeHandler.removeCallbacksAndMessages(null);
            timeHandler = null;
        }
        if (weatherEs != null && !weatherEs.isShutdown()) {
            try {
                weatherEs.shutdownNow();
                weatherEs = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
